import {reqRegister, reqLogin, reqAuth, reqUpdate} from '../api';
import {AUTH_SUCCESS, DO_LOGOUT} from './action-types';

//同步action
export const authSuccess = (user) => ({type:AUTH_SUCCESS, data:user})
export const doLogout = () => ({type:DO_LOGOUT})

//异步action
export function registerAsync({user, pwd, type},callBack) {

    return async dispatch => {
        let response = await reqRegister({user, pwd, type});

        let {code, data, token, msg} = response.data;
        if(code === 0){
            localStorage.setItem("token",token);
            dispatch(authSuccess(data))
        }
        callBack && callBack(code, msg)

    }
}

export function loginAsync({user, pwd}, callBack) {

    return async dispatch => {
        let response = await reqLogin({user, pwd});
        let {code, data, token, msg} = response.data;
        if(code === 0){
            localStorage.setItem("token",token);
            dispatch(authSuccess(data))
        }
        callBack && callBack(code, msg, data)

    }
}

export function updateInfoAsync(userData, callBack) {
    return async dispatch => {

        let response = await reqUpdate(userData);
        let {code, data, token, msg} = response.data;
        if(code === 0){
            //更新token
            localStorage.setItem('token',token)
            //更新状态
            dispatch(authSuccess(data))
        }
        callBack && callBack(code, msg)

    }
}

export function  authAsync(user, callBack) {
    let token = localStorage.getItem('token');
    if(user !== '' || !token){
        return {type:'default'}
    }
    return async dispatch => {

        let response = await reqAuth(token);
        let {code, data, msg} = response.data;
        if(code === 0){
            dispatch(authSuccess(data))
        }
        callBack && callBack(code, msg)

    }
}